package com.ynsj.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynsj.domain.SysUserRole;
import com.ynsj.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynsj.domain.SysUser;
import com.ynsj.mapper.SysUserMapper;
import com.ynsj.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Page<SysUser> findByPage(Page<SysUser> sysUserPage, String mobile, String fullname) {
        sysUserPage.addOrder(OrderItem.desc("last_update_time"));
        Page<SysUser> page = page(sysUserPage, new LambdaQueryWrapper<SysUser>()
                .like(!StringUtils.isEmpty(mobile), SysUser::getMobile, mobile)
                .like(!StringUtils.isEmpty(fullname), SysUser::getFullname, fullname));
        List<SysUser> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)){
            records.forEach(record -> {
                List<SysUserRole> sysUserRoles = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, record.getId()));
                if (!CollectionUtils.isEmpty(sysUserRoles)) {
                    record.setRole_strings(sysUserRoles.stream().map(sysUserRole -> sysUserRole.getRoleId().toString()).collect(Collectors.joining(",")));
                }
            });
        }

        return page;
    }

    @Override
    @Transactional
    public boolean addSysUser(SysUser sysUser) {
        String password = sysUser.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(bCryptPasswordEncoder.encode(password));//密码加密
        boolean save = super.save(sysUser);
        if (save) {
            //处理用户角色
            if (!StringUtils.isEmpty(sysUser.getRole_strings())) {
                String roleStrings = sysUser.getRole_strings();
                String[] split = roleStrings.split(",");
                List<SysUserRole> sysUserRoles = new ArrayList<>();
                for (String s : split) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(s));
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRoles.add(sysUserRole);
                }
                sysUserRoleService.saveBatch(sysUserRoles);
            }
        }
        return save;
    }

    @Override
    @Transactional
    public boolean updateSysUser(SysUser sysUser) {
        boolean update = super.updateById(sysUser);
        if (update){
            //先清空该用户角色数据
            sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,sysUser.getId()));
            //处理用户角色
            if (!StringUtils.isEmpty(sysUser.getRole_strings())) {
                String roleStrings = sysUser.getRole_strings();
                String[] split = roleStrings.split(",");
                List<SysUserRole> sysUserRoles = new ArrayList<>();
                for (String s : split) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(s));
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRoles.add(sysUserRole);
                }
                sysUserRoleService.saveBatch(sysUserRoles);
            }
        }
        return update;
    }

    @Override
    @Transactional
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        boolean remove = super.removeByIds(idList);
        if (remove){
            sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,idList));
        }
        return remove;
    }
}
